package com.fungo.orderservice.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class UserService {

    private final RestTemplate restTemplate;
    private final String userServiceUrl;
    
    @Autowired
    public UserService(RestTemplate restTemplate, 
                      @Value("${user.service.url}") String userServiceUrl) {
        this.restTemplate = restTemplate;
        this.userServiceUrl = userServiceUrl;
    }
    
    /**
     * Verify if a user exists by calling the user-service
     */
    public boolean userExists(String userId) {
        try {
            log.info("Checking if user exists: {}", userId);
            String url = userServiceUrl + "/users/" + userId;
            
            ResponseEntity<Object> response = restTemplate.getForEntity(url, Object.class);
            return response.getStatusCode() == HttpStatus.OK;
            
        } catch (HttpClientErrorException.NotFound e) {
            log.warn("User {} not found", userId);
            return false;
        } catch (Exception e) {
            log.error("Failed to verify user {}: {}", userId, e.getMessage(), e);
            throw new RuntimeException("Failed to verify user", e);
        }
    }
} 